<script setup lang="ts">
import { ref, computed } from 'vue';

interface Image {
  id: number;
  name: string;
  url: string;
  [key: string]: any;
}
const props = defineProps<{ images: Image[], index?: number }>();
const currentIndex = ref(props.index ?? 0);
const currentImage = computed(() => props.images.length > 0 ? props.images[currentIndex.value] : null);

const prevImage = () => {
  if (props.images.length > 1) {
    currentIndex.value = (currentIndex.value - 1 + props.images.length) % props.images.length;
  }
}
const nextImage = () => {
  if (props.images.length > 1) {
    currentIndex.value = (currentIndex.value + 1) % props.images.length;
  }
}
</script>

<template>
  <div class="image-preview flex-center-center">
    <template v-if="currentImage">
      <img :src="currentImage.url" :alt="currentImage.name"  />
      <p>{{ currentImage.name }}</p>
    </template>
    <div v-else>
      <p>No image available</p>
    </div>
    
    <!-- 左右两侧切换图片 -->
    <template v-if="props.images.length > 1">
      <div class="aside left flex--center pointer" @click="prevImage" >
        <el-icon size="25"><ArrowLeftBold /></el-icon>
      </div>
      <div class="aside right flex--center pointer" @click="nextImage">
        <el-icon size="25"><ArrowRightBold /></el-icon>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.image-preview {
  width: 100%;
  height: 100%;
  position: relative;
  border: 1px solid #efefef;
  img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }
  p {
    position: absolute;
    bottom: 0;
  }
}
/* 左右两侧切换图片 */
.aside {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  height: 40px;
  &.left {
    left: 0;
  }
  &.right {
    right: 0;
  }
}
</style>